import path from 'path';
import fse from 'fs-extra';
import { parseRootFile, unzip } from '@/modules/book/epub-parse';

class EpubBook {
  bookPath: string;
  file: string;
  fileName: string;
  size: number;

  constructor(bookPath, file) {
    this.bookPath = bookPath;
    this.file = file;
    this.fileName = file.originalname;
    this.size = file.size;
  }

  async parse() {
    // 生成临时文件
    const tmpDir = path.join(process.cwd(), 'vben', 'temp-book');
    const tmpFile = path.resolve(tmpDir, this.fileName);
    fse.copySync(this.bookPath, tmpFile);
    // 解压临时文件
    const tmpUnzipDirName = this.fileName.replace('.zip', '');
    const tmpUnzipDir = path.resolve(tmpDir, tmpUnzipDirName);
    // 创建文件夹
    fse.mkdirpSync(tmpUnzipDir);
    // 解压
    unzip(tmpFile, tmpUnzipDir);
    // 解析
    const rootFile = await parseRootFile(tmpUnzipDir);
    // console.log('rootFile', rootFile);

    // 操作完成之后删除文件
    fse.removeSync(tmpFile);
    fse.removeSync(tmpUnzipDir);
    return rootFile;
  }
}

export default EpubBook;
